from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv

load_dotenv()  # 加载环境变量

DATABASE_URL = os.getenv(
    "DATABASE_URL", "mysql+mysqlconnector://root:jf4SswsRthTTgan@localhost:3306/trading"
)


engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,  # Enable connection health check
    pool_size=10,  # Increase this based on your app's needs
    max_overflow=20,  # Allow extra connections if the pool is full
    pool_recycle=1800,  # Recycle connections after 1800 seconds (30 minutes)
    pool_timeout=30,  # Wait time for an available connection (seconds)
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


# Dependency，用于在API请求期间获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
